package com.weishenai.customerassistant.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class UniqueIdUtil {

    /**
     * KEYS[1] 唯一标识key
     * ARGV[1] 过期时间
     */
    private static final String UniqueIdScript = "local result=redis.call('setnx',KEYS[1],0); " +
            "if(tonumber(result)==1) then " +
            "redis.call('expire',KEYS[1],ARGV[1]);" +
            "end; " +
            "return redis.call('incrby',KEYS[1],1); ";
    private static final String expireTimes = "1";

    /**
     * 利用redis的单线程实现分布式下面的全局ID
     * 前缀是当前时间的毫秒值，后者是redis的自增的数字。
     * 两个值拼接以后生成19位的全局唯一id
     *
     * @param redisTemplate
     * @param flag 是否需要格式化结果
     * @return 全局ID
     */
    public static String getResultId(RedisTemplate redisTemplate, boolean flag) {
        String millis = String.valueOf(System.currentTimeMillis());
        String redisKey = "UniqueId" + millis;
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add(redisKey);
        RedisScript redisUnLockScript = RedisScript.of(UniqueIdScript, Long.class);
        Long result = (Long) redisTemplate.execute(redisUnLockScript, keyList, expireTimes);
        if (flag) {
            DecimalFormat df = new DecimalFormat("000000");
            return millis + df.format(result);
        }
        return result + millis;
    }
}
